package com.toocms.jinjuhang.ui.login

import android.app.Application
import android.os.Bundle
import androidx.databinding.ObservableField
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.GsonUtils
import com.google.gson.reflect.TypeToken
import com.toocms.jinjuhang.config.Constants
import com.toocms.jinjuhang.config.Urls
import com.toocms.jinjuhang.config.UserRepository
import com.toocms.jinjuhang.data.AccountInfoData
import com.toocms.jinjuhang.data.User
import com.toocms.jinjuhang.data.system.Pic2idData
import com.toocms.jinjuhang.dialog.options.OptionsDialog
import com.toocms.jinjuhang.ui.login.forget_password.ForgetPasswordCheckFgt
import com.toocms.jinjuhang.ui.login.register.RegisterFgt
import com.toocms.jinjuhang.ui.login.verify_account.VerifyAccountFgt
import com.toocms.jinjuhang.widget.view_model.requestData
import com.toocms.tab.base.BaseActivity
import com.toocms.tab.base.BaseModel
import com.toocms.tab.base.BaseViewModel
import com.toocms.tab.binding.command.BindingAction
import com.toocms.tab.binding.command.BindingCommand
import com.toocms.tab.share.TabShare
import com.toocms.tab.share.listener.OnAuthListener
import com.toocms.tab.share.login.PlatformUser
import com.umeng.socialize.bean.SHARE_MEDIA

class LoginModel(application: Application) : BaseViewModel<BaseModel>(application) {

    val accountObservableField = ObservableField<String>()
    val passwordObservableField = ObservableField<String>()

    val loginClickBindingCommend = BindingCommand<BindingAction>(BindingAction {
        login(
            "1",
            account = accountObservableField.get() ?: "",
            password = passwordObservableField.get() ?: ""
        )
    })
    val wechatClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        TabShare.getOneKeyLogin()
            .showUser(true, SHARE_MEDIA.WEIXIN, object : OnAuthListener() {
                override fun onComplete(
                    share_media: SHARE_MEDIA?,
                    action: Int,
                    user: PlatformUser?
                ) {

                }

                override fun onComplete(
                    share_media: SHARE_MEDIA?,
                    action: Int,
                    map: MutableMap<String, String>?
                ) {
                    super.onComplete(share_media, action, map)
                    val openid = map?.get("uid") ?: return
                    val unionid = map?.get("unionid") ?: return
                    val name = map?.get("name") ?: ""
                    val iconurl = map?.get("iconurl") ?: ""
                    if (iconurl.isNullOrEmpty()) {
                        login("2", openid = openid, unionid = unionid, nickname = name)
                    } else {
                        val params = mapOf(Pair("url", iconurl))
                        requestData(
                            Urls.System.PIC_2_ID,
                            params,
                            resultClass = Pic2idData::class.java,
                            result = {
                                login(
                                    "2",
                                    openid = openid,
                                    unionid = unionid,
                                    nickname = name,
                                    avatar = it.id
                                )
                            })
                    }

                }
            })
    })
    val forgetPasswordClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        startFragment(ForgetPasswordCheckFgt::class.java)
    })
    val registerClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        startFragment(RegisterFgt::class.java)
    })


    private fun login(
        accountType: String,
        account: String = "",
        password: String = "",
        openid: String = "",
        unionid: String = "",
        nickname: String = "",
        avatar: String = ""
    ) {
        val params = mutableMapOf<String, String?>()
        params["account_type"] = accountType
        params["account"] = account
        params["password"] = password
        params["openid"] = openid
        params["unionid"] = unionid
        params["nickname"] = nickname
        params["avatar"] = avatar
        requestData(Urls.Login.LOGIN, params, resultClass = User::class.java, result = {
            when (it.errcode) {
                "redundancy_account" -> {
                    if (it.account_info.isNullOrEmpty()) return@requestData
                    OptionsDialog().apply {
                        optionsItems = GsonUtils.fromJson(
                            it.account_info,
                            object : TypeToken<List<AccountInfoData>>() {

                            }.type
                        )
                        title = "请选择手机号"
                        isShowConfirm = true
                        onOptionClickListener = { option, tag ->
                            if (option is AccountInfoData) {
                                val bundle = Bundle()
                                bundle.putString(
                                    Constants.BundleKey.KEY_MEMBER_ID,
                                    option.member_id
                                )
                                bundle.putString(
                                    Constants.BundleKey.KEY_ACCOUNT,
                                    option.account
                                )
                                bundle.putString(Constants.BundleKey.KEY_OPEN_ID, openid)
                                bundle.putString(Constants.BundleKey.KEY_UNION_ID, unionid)
                                startFragment(VerifyAccountFgt::class.java, bundle)
                            }
                        }
                        show(
                            (ActivityUtils.getTopActivity() as BaseActivity).supportFragmentManager,
                            null
                        )
                    }
                }
                else -> {
                    UserRepository.updateUser(it)
                    UserRepository.setLogin(true)
                    finishFragment()
                }
            }
        },
            error = {
                if (!openid.isNullOrEmpty() && !unionid.isNullOrEmpty()) {
                    val bundle = Bundle().apply {
                        putString(Constants.BundleKey.KEY_OPEN_ID, openid)
                        putString(Constants.BundleKey.KEY_UNION_ID, unionid)
                        putString(Constants.BundleKey.KEY_AVATAR, avatar)
                        putString(Constants.BundleKey.KEY_NICKNAME, nickname)
                    }
                    startFragment(RegisterFgt::class.java, bundle)
                }else{
                    showToast(it.message)
                }
            })
    }

    override fun onStop() {
        super.onStop()
        TabShare.release()
    }
}